package com.nx.platform.es.biz.query.agg.handler;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Table;
import com.nx.platform.es.biz.wrapper.parser.StatementOperator;
import com.nx.platform.es.bean.modle.agg.AggField;
import com.nx.platform.es.biz.query.agg.AggRequestContext;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;

import java.util.List;


/**
 * @author
 * @since 2016年10月15日
 */
public enum AggHandler implements AggRequestHandler {

    INSTANCE;

    @Override
    public void handle(AggRequestContext context) {
        Table<String, StatementOperator, List<String>> paramsTable = context.getParamsTable();
        List<String> termList = paramsTable.get("term", StatementOperator.EQUAL);
        List<String> sortList = paramsTable.get("sort", StatementOperator.EQUAL);
        Preconditions.checkArgument(CollectionUtils.isNotEmpty(termList), "params error, term not found");
        String term = termList.get(0);
        String sort = "";
        if (CollectionUtils.isNotEmpty(sortList)) {
            sort = sortList.get(0);
        }
        for (AggField aggField : context.getAggFields()) {
            if (term.equals(aggField.getFace())) {
                TermsAggregationBuilder termsBuilder = aggField.handle(ImmutableMap.of("sort", sort));
                if (termsBuilder != null) {
                    context.getRequest().source().aggregation(termsBuilder);
                    StringBuilder sb = context.getTrace();
                    sb.append("&term").append(StatementOperator.EQUAL.getSymbol()).append(term);
                    if (!"".equals(sort)) {
                        sb.append("&termsort").append(StatementOperator.EQUAL.getSymbol()).append(sort);
                    }
                    return;
                }
            }
        }
        throw new IllegalArgumentException("term field not support: " + term);
    }

}
